package com.puyuba.puyuba.view.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.flyco.tablayout.SlidingTabLayout;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.SkinApplication;
import com.pyb.java.basemodule.BaseFragment;
import com.puyuba.puyuba.bean.GetTeacherBean;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.puyuba.puyuba.network.UserApi;
import com.pyb.java.commonutil.utils.NetUtil;
import com.pyb.java.commonutil.ToastHelper;

import com.puyuba.puyuba.view.adapter.GetTeacherAdatper;
import com.puyuba.puyuba.view.viewpager.WrapViewPager;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

/**
 * 消息模块第三个fragment 找顾问页面
 */
public class MessageFindTeacherFragment extends BaseFragment {
    private EditText etFindteacher;
    private SlidingTabLayout tlFindteacher;
    private WrapViewPager vpFindTeacher;
    private TextView tvSearchStu2;
    private SmartRefreshLayout srlMsgTeacher;
    private RecyclerView rclListFindteacher;

    private String[] mTitles  = {"职业考证", "学历考证", "职业技能"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private GetTeacherAdatper mAdapter;
    private int localpage = 1;//本地加载的页数
    private int last_page = 1;//最大有几页
    private String name = "";

    @Override
    public void initView() {

        etFindteacher = (EditText) getActivity().findViewById(R.id.et_findteacher);
        tlFindteacher = (SlidingTabLayout) getActivity().findViewById(R.id.tl_findteacher);
        vpFindTeacher = (WrapViewPager) getActivity().findViewById(R.id.vp_find_teacher);
        tvSearchStu2 = (TextView) getActivity().findViewById(R.id.tv_search_stu2);
        srlMsgTeacher = (SmartRefreshLayout) getActivity().findViewById(R.id.srl_msg_teacher);
        rclListFindteacher = (RecyclerView) getActivity().findViewById(R.id.rcl_list_findteacher);
        initListener();
        rclListFindteacher.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new GetTeacherAdatper(R.layout.item_get_teacher);
//        mAdapter.bindToRecyclerView(rclListFindteacher);
        rclListFindteacher.setAdapter(mAdapter);

        srlMsgTeacher.setRefreshHeader(new ClassicsHeader(getContext()));
        srlMsgTeacher.setRefreshFooter(new ClassicsFooter(getContext()));
        srlMsgTeacher.setOnRefreshListener(refreshlayout -> {
            boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
            if (mobileConnected) {
                localpage = 1; //每次下拉刷新 都置为1
                typelist(0, CacheUserInfo.getInstance().getId(),0,"",false);
            } else {
                ToastHelper.showToast("网络未连接，请检查网络状态");
                if (srlMsgTeacher!= null){
                    srlMsgTeacher.finishRefresh();
                }
            }
        });
        srlMsgTeacher.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                boolean mobileConnected = NetUtil.isNetworkAvailable(SkinApplication.sContext);
                if (mobileConnected) {
                    localpage++;
                    typelist(localpage, CacheUserInfo.getInstance().getId(),0,"",true);
                } else {
                    ToastHelper.showToast("网络未连接，请检查网络状态");
                    if (srlMsgTeacher!= null){
                        srlMsgTeacher.finishLoadMore();
                    }
                }
            }
        });
//        老师下面三个tab暂时隐藏
//        initFragments();
//        initTab();
        typelist(0, CacheUserInfo.getInstance().getId(),0,"",false);
        tvSearchStu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = etFindteacher.getText().toString().trim();
                typelist(localpage, CacheUserInfo.getInstance().getId(),0,name,true);
            }
        });

    }

    private void initListener() {
        tvSearchStu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name = etFindteacher.getText().toString().trim();
                typelist(0, CacheUserInfo.getInstance().getId(),0,"",false);
            }
        });
    }
    public static MessageFindTeacherFragment getInstance(String type) {
        MessageFindTeacherFragment messageOneFragment = new MessageFindTeacherFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        messageOneFragment.setArguments(args);
        return messageOneFragment;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message_find_teacher;
    }

    //查询老师
    private void typelist(int page,int uid,int type,String keyword,boolean isLoadMore) {
        if (!isLoadMore) {
            localpage = 1;
        }
        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("uid", uid);
        map.put("type", type);
        map.put("keyword", keyword);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);
        RetrofitManger.getInstance().createService(UserApi.class)
                .typelist(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<GetTeacherBean>>applySchedulers())
                .subscribe(new ResponseObserve<GetTeacherBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<GetTeacherBean> responseEntity) {
                        closeLoadingDialog();

                        if (localpage <= last_page && localpage != 1) {
                            mAdapter.addData(responseEntity.getData().getList());
                        } else {
                            mAdapter.setNewData(responseEntity.getData().getList());
                        }
                        last_page = responseEntity.getData().getPage().getLast_page();

                        if (localpage >= last_page) {
                            srlMsgTeacher.finishLoadMoreWithNoMoreData();  //全部加载完成,没有数据了调用此方法
//                                mAdapter.loadMoreEnd();
                        } else {
                            srlMsgTeacher.finishLoadMore();
//                                mAdapter.loadMoreComplete();
                        }

                    }

                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        if (errorMsg != null&&!errorMsg.equals("")){
                            ToastHelper.show(errorMsg);
                        }else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        if (srlMsgTeacher!= null){
                            srlMsgTeacher.finishRefresh();
                        }
                    }
                });

    }

    private void initFragments() {
        mFragments.clear();
        mFragments.add(MessageFinteaFragment1.getInstance("职业考证"));
        mFragments.add(MessageFinteaFragment2.getInstance("学历考证"));
        mFragments.add(MessageFinteaFragment3.getInstance("职业技能"));

    }
    private void initTab() {
        vpFindTeacher.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
        vpFindTeacher.setOffscreenPageLimit(2);
        tlFindteacher.setViewPager(vpFindTeacher);

        tlFindteacher.setOnTabSelectListener(new com.flyco.tablayout.listener.OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                vpFindTeacher.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        vpFindTeacher.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

            @Override
            public void onPageSelected(int position) {
                tlFindteacher.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) { }
        });
        vpFindTeacher.setCurrentItem(0);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }
}
